﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using NetFramework;
using NetFramework.AsyncSocketServer;
namespace GameServer
{
    public partial class Form1 : Form
    {
        //主窗体
        public static Form1 mainform = null;
        //server服务
        public static IServerSocket serversocket;
        //所有的桌子
        public static List<Table> tables = new List<Table>();
        //玩家列表 第一个参数是 ConnectID,第二个 参数是用户名
        public static Dictionary<string, string> userlistdata = new Dictionary<string, string>();
        //获取主窗体
        public static Form1 GetMainForm()
        {
            if (mainform != null)
            {
                return mainform;
            }
            return null;
        }
        //调试信息窗体
        public static MessageBOX messagelist;
        //构造函数
        public  Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            Form1.mainform = this;
        }
        //服务器启动
        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button2.Enabled = true;
            //不断获取当前连接数
            timer1.Enabled = true;
            if (checkBox1.Checked)
            {
                if (messagelist == null)
                {
                    messagelist = new MessageBOX(this);
                }
                messagelist.Show();
            }
            tables.Clear();
            userlistdata.Clear();
            listBox1.Items.Clear();
            StartServer();
        }
        //添加一个玩家
        public static void AddUser(string connectid,AsyncUserToken token)
        {
            string msg = "一个新的玩家{0}加入!当前有{1}个玩家";
            msg = string.Format(msg, connectid,serversocket.NumConnectedSockets);
            Debug("NEW  "+msg);
            try
            {
                Form1 form = Form1.GetMainForm();
                if (form != null)
                {
                    form.toolStripStatusLabel1.Text = "一个新的玩家加入!";
                }
                Table table = FindEmptyTable();
                //必须是这种桌子不在游戏中,才运行加人!
                if (table != null)
                {
                    if (table.TABLESTATE == TableState.wait)
                    {
                        table.AddUser(connectid, token);
                    }
                }
                else
                {
                    //新建一个桌子
                    Table tablenew = new Table();
                    tablenew.AddUser(connectid, token);
                    tables.Add(tablenew);
                }
            }
            catch (Exception ex)
            {
                DebugError("异常来自于:Form1.cs AddUser方法!  "+ex.ToString());
            }
        }
        /// <summary>
        /// 发送消息到桌子的其他玩家
        /// </summary>
        /// <param name="connectid"></param>
        /// <param name="message"></param>
        public static void SendTableOtherMessage(string connectid,string message)
        {
            try
            {
                Table findtable = null;
                foreach (Table table in tables)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (table.users[i].connstringid == connectid)
                        {
                            findtable = table;
                            break;
                        }
                    }
                }
                if (findtable != null)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (findtable.users[i].connstringid != connectid)
                        {
                            byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
                            Form1.serversocket.Send(findtable.users[i].connstringid, data);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DebugError("异常来自于 Form1.cs SendTableOtherMessage方法  " + ex.ToString());
            }
        }
        /// <summary>
        /// 发送自己的位置到其他玩家
        /// </summary>
        /// <param name="connectid"></param>
        /// <param name="username"></param>
        public static void SendTableOtherNames(string connectid, string username)
        {
            try
            {
                int index = -1;
                Table findtable = null;
                foreach (Table table in tables)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (table.users[i].connstringid == connectid)
                        {
                            table.users[i].username = username;
                            findtable = table;
                            index = i;
                            break;
                        }
                    }
                }
                if (findtable != null)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (findtable.users[i].connstringid == connectid)
                        {
                            byte[] data = System.Text.Encoding.UTF8.GetBytes("myinde*" + i.ToString() + "*");
                            Form1.serversocket.Send(findtable.users[i].connstringid, data);
                            break;
                        }
                    }
                    byte[] userdata = System.Text.Encoding.UTF8.GetBytes("weizhi*" + username + "," + index.ToString() + "*");
                    //把别人的位置告诉自己
                    for (int i = 0; i < 3; i++)
                    {
                        if (findtable.users[i].connstringid != connectid && findtable.users[i].connstringid != "")
                        {
                            //返回这个位置的索引和用户名
                            byte[] data = System.Text.Encoding.UTF8.GetBytes("weizhi*" + findtable.users[i].username + "," + i.ToString() + "*");
                            Form1.serversocket.Send(connectid, data);
                            Form1.serversocket.Send(findtable.users[i].connstringid, userdata);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DebugError("异常来自于 Form1.cs SendTableOtherNames  " + ex.ToString());
            }
        }
        /// <summary>
        /// 发送消息到桌子的其他玩家
        /// </summary>
        /// <param name="connectid"></param>
        /// <param name="message"></param>
        public static void SendTableALL(string connectid, string message)
        {
            try
            {
                Table findtable = null;
                foreach (Table table in tables)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (table.users[i].connstringid == connectid)
                        {
                            findtable = table;
                            break;
                        }
                    }
                }
                if (findtable != null)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
                        Form1.serversocket.Send(findtable.users[i].connstringid, data);
                    }
                }
            }
            catch (Exception ex)
            {
                DebugError("异常来自于 Form1.cs SendTableALL  " + ex.ToString());
            }
        }
        /// <summary>
        /// 找到桌子中空着的位置
        /// </summary>
        /// <returns></returns>
        public static Table FindEmptyTable()
        {
            try
            {
                foreach (Table table in tables)
                {
                    for (int i = 0; i < table.users.Count; i++)
                    {
                        if (table.users[i].state == STATE.none)
                        {
                            return table;
                        }
                    }
                }
                return null;
            }
            catch(Exception ex)
            {
                DebugError("异常来自于 Form1.cs FindEmptyTable  " + ex.ToString());
                return null;
            }
        }
        /// <summary>
        /// 找对应id所在的桌子!
        /// </summary>
        /// <param name="connectid"></param>
        /// <returns></returns>
        public static Table FindIDInTable(string connectid,out int id)
        {
            id = -1;
            try
            {
                foreach (Table table in tables)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (table.users[i].connstringid == connectid)
                        {
                            id = i;
                            return table;
                        }
                    }
                }
                return null;
            }
            catch (Exception ex)
            {
                DebugError("异常来自于 Form1.cs FindIDInTable " + ex.ToString());
                return null;
            }
        }
        /// <summary>
        /// 删除断开的连接
        /// </summary>
        /// <param name="connectid"></param>
        public static void DelClient(string connectid)
        {
            string msg = "一个玩家{0}离开!当前有{1}个玩家!";
            msg = string.Format(msg, connectid,serversocket.NumConnectedSockets);
            Debug("DIS  " + msg);
            try
            {
                Form1 form = Form1.GetMainForm();
                if (form != null)
                {
                    form.toolStripStatusLabel1.Text = "一个玩家退出游戏!";
                }
                userlistdata.Remove(connectid);
                int index = -1;
                //找到桌子
                Table table = FindIDInTable(connectid, out index);
                //在线的数量减去1
                table.OnLineCount--;
                if (table != null && index != -1)
                {
                    //设置为这个位子为离线
                    table.users[index].OffLine();
                }
                string text = "exitga*" + index.ToString() + "*";
                byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
                for (int i = 0; i < table.users.Count; i++)
                {
                    if (i != index)
                    {
                        Form1.serversocket.Send(table.users[i].connstringid, data);
                    }
                }
            }
            catch (Exception ex)
            {
                DebugError("异常来自于: Form1.cs DelClient  " + ex.ToString());
            }
        }
        /// <summary>
        /// 更改状态为准备
        /// </summary>
        /// <param name="connectid"></param>
        public static void ChangeZhunBei(string connectid)
        {
            try
            {
                foreach (Table table in tables)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (table.users[i].connstringid == connectid)
                        {
                            table.users[i].Zhunbei();
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DebugError("异常来自于:Form1.cs ChangeZhunBei " + ex.ToString());
            }
        }
        /// <summary>
        /// 启动服务器
        /// </summary>
        private void StartServer()
        {
            try
            {
                int count = 0;
                if (!int.TryParse(textBox1.Text, out count))
                {
                    MessageBox.Show("连接数量错误!请重新填写!");
                    return;
                }
                int buffersize = 0;
                if (!int.TryParse(textBox2.Text, out buffersize))
                {
                    MessageBox.Show("缓冲区填写错误!请重新填写!");
                    return;
                }
                serversocket = new IServerSocket(count, buffersize);
                serversocket.Init();
                int port = 0;
                if (!int.TryParse(textBox3.Text, out port))
                {
                    MessageBox.Show("端口填写错误,请重新填写!");
                    return;
                }
                serversocket.Start(port);
                serversocket.OnClientRead += new EventHandler<NetFramework.AsyncUserToken>(clientread);
                serversocket.OnClientDisconnect += new EventHandler<NetFramework.AsyncUserToken>(disconnect);
            }
            catch (Exception ex)
            {
                DebugError("服务端启动失败......! 异常来自于 Form1.cs StartServer  "+ex.ToString());
            }
        }
        string connectid = "";
        public static void Debug(string message)
        {
            if (messagelist != null)
            {
                messagelist.AddMessage(message);
            }
        }
        public static void DebugError(string message)
        {
            if (messagelist != null)
            {
                messagelist.AddMessage(message);
            }
        }
        /// <summary>
        /// 接受到数据事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="toker"></param>
        public void clientread(object sender,NetFramework.AsyncUserToken toker)
        {
            try
            {
                //获取toker的桌子
                if (toker.table == null)
                {
                    toker.table = FindTable(toker);
                }
                connectid = toker.ConnectionId;
                Array.Copy(toker.ReceiveBuffer, toker.Offset, toker.databuffer, toker.end, toker.BytesReceived);
                toker.end += toker.BytesReceived;
                int data1 = toker.databuffer[toker.offset];
                while (toker.end - toker.offset >= data1 + 1)
                {
                    string text = System.Text.Encoding.UTF8.GetString(toker.databuffer, toker.offset + 1, data1);
                    this.toolStripStatusLabel1.Text = text;
                    string text1 = text.Substring(0, 5);
                    string msg = "接收到玩家{0}的消息:{1}";
                    msg = string.Format(msg,toker.ConnectionId.ToString(), text);
                    Debug("READ   " + msg);
                    /*
                     * start开始游戏 参数用户名
                     * dengl发送了自己的用户名
                   */
                    if (text1 == "start")
                    {
                        ChangeZhunBei(toker.ConnectionId);
                        if (toker.table != null)
                        {
                            toker.table.jiaodizhu();
                        }
                    }
                    else if (text1 == "dengl")
                    {
                        text = text.Substring(6, text.Length - 7);
                        //由于我们是以逗号分隔的,所以用户提交的逗号,需要替换好,我们替换为了'.'号
                        text=text.Replace(',','.');
                        Form1.SendTableOtherNames(toker.ConnectionId, text);
                        userlistdata.Add(toker.ConnectionId, text);
                        ShowData(userlistdata);
                    }
                    else if (text1 == "jiaod")
                    {
                        text = text.Substring(6, text.Length - 7);
                        string[] data = text.Split(',');
                        if (toker.table != null)
                        {
                               toker.table.jiaodizhu(int.Parse(data[0]), int.Parse(data[1]));
                        }
                    }
                    //接受到出牌的命令
                    else if (text1 == "chupa")
                    {
                        text = text.Substring(6, text.Length - 7);
                        if (toker.table != null)
                        {
                            toker.table.ProcessTableMessage(text);
                        }
                    }
                    toker.offset = toker.offset + data1 + 1;
                    data1 = toker.databuffer[toker.offset];
                }
                if (toker.end == toker.offset)
                {
                    toker.offset = 0;
                    toker.end = 0;
                }
            }
            catch (Exception ex)
            {
                
                DebugError("异常来自于:Form1.cs 353行   " + ex.ToString());
            }
            System.Threading.Thread.Sleep(10);
        }
        public void ShowData(Dictionary<string, string> userdata)
        {
            try
            {
                listBox1.Items.Clear();
                foreach (KeyValuePair<string, string> pair in userdata)
                {
                    obj1 obj = new obj1();
                    obj.username = pair.Value;
                    obj.connectid = pair.Key;
                    listBox1.Items.Add(obj);
                    //listBox1.Items.Add(pair.Value);
                }
            }
            catch (Exception ex)
            {
                DebugError("异常来自于 Form1.cs ShowData  " + ex.ToString());
            }
        }
        /// <summary>
        /// 查找桌子
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Table FindTable(AsyncUserToken user)
        {
            try
            {
                foreach (Table tabel in tables)
                {
                    foreach (User usertemp in tabel.users)
                    {
                        if (usertemp.token == user)
                        {
                            return tabel;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DebugError("异常来自于 Form1.cs FindTable  " + ex.ToString());
            }
            return null;
        }
        /// <summary>
        /// 断开客户端事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="toker"></param>
        public void disconnect(object sender, NetFramework.AsyncUserToken toker)
        {
            try
            {
                DelClient(toker.ConnectionId);
                ShowData(userlistdata);
            }
            catch (Exception ex)
            {
                DebugError("异常来自于 From1.cs disconnect  " + ex.ToString());
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            this.toolStripStatusLabel1.Text = "服务端已经停止......!";
            button2.Enabled = false;
            button1.Enabled = true;
            serversocket.Shutdown();
            //清空桌子
            tables.Clear();
        }
        /// <summary>
        /// 单独给某个用户发送消息,或者群发消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            //要发送的数据
            string text = textBox4.Text;
            byte[] data = System.Text.Encoding.UTF8.GetBytes(text);
            //群发
            if (checkBox2.Checked)
            {
                foreach (KeyValuePair<string, string> temp in userlistdata)
                {
                    try
                    {
                        Form1.serversocket.Send(temp.Key.ToString(), data);
                    }
                    catch (Exception ex)
                    {
                        Form1.DebugError(ex.ToString());
                    }
                }
                return;
            }
            int index = this.listBox1.SelectedIndex;
            if (index >= 0 && index < this.listBox1.Items.Count)
            {
                obj1 user = (obj1)this.listBox1.SelectedItem;
                serversocket.Send(user.connectid, data);
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (serversocket != null)
            {
                label6.Text = serversocket.NumConnectedSockets.ToString();
               
            }
            label10.Text = tables.Count.ToString();
        }
        //开启和关闭调试窗口
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                if (messagelist == null)
                {
                    messagelist = new MessageBOX(this);
                    messagelist.Show();
                }
            }
            else
            {
                if (messagelist != null)
                {
                    messagelist.Close();
                    messagelist = null;
                }
            }
        }
        public void SetCheckBox(bool flag)
        {
            if (flag)
            {
                checkBox1.Checked = true;
            }
            else
            {
                checkBox1.Checked = false;
            }
        }
        private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("作者:Aladdin 博客: http://blog.csdn.net/dingxiaowei2013");
        }
        /// <summary>
        /// 搜索玩家
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            string findname = textBox5.Text;
            if (findname == "")
            {
                return;
            }
            else
            {
                int index=listBox1.FindString(findname);
                listBox1.SetSelected(index, true);
            }
        }
        /// <summary>
        /// 剔除一个用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            obj1 obj = (obj1)listBox1.SelectedItem;
            if (obj != null)
            {
                serversocket.Disconnect(obj.connectid);
            }
        }

     
    }
    public class obj1
    {
        public string username;
        public string connectid;
        public override string ToString()
        {
            return username;
        }
    }
}
